package com.lmx.web.controller.thirdPart;

import com.lmx.common.context.ActionContextHolder;

import com.lmx.local.business.LiveStreamListener;
import com.lmx.local.business.VideoProcessor;
import com.lmx.common.util.CommonUtil;

import com.lmx.persistence.service.ALiService;
import com.lmx.persistence.service.CustomerService;
import com.lmx.persistence.service.DeviceService;
import com.lmx.persistence.service.EmployeeService;
import com.lmx.persistence.service.LocalHbeaconService;
import com.lmx.persistence.service.MessageService;
import com.lmx.persistence.service.NursingService;
import com.lmx.persistence.service.StatService;
import com.lmx.persistence.service.TenantService;
import com.lmx.persistence.service.TestService;
import com.lmx.persistence.service.TimerService;
import com.lmx.persistence.service.WeiXinService;
import com.lmx.repoDomain.tmodel.LsMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.WebSocketSession;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/*-
 * 测试处理接口
 */

@Controller
@RequestMapping("/access/test")
public class TestController {
	private static Log logger = LogFactory.getLog(TestController.class);

//	 @PersistenceContext
//	 private EntityManager em;

	@Autowired
	private TimerService sService;

	@Autowired
	private TestService testService;

	@Autowired
	private LocalHbeaconService lService;

	@Autowired
	private WeiXinService wService;

	@Autowired
	private NursingService nService;

	@Autowired
	private DeviceService dService;

	@Autowired
	private EmployeeService employeeService;

	@Autowired
	private NursingService nursingService;

	@Autowired
	private CustomerService cService;

	@Autowired
	private ALiService aLiService;

	@Autowired
	private StatService statService;

	@Autowired
	private TenantService tenantService;

	@Autowired
	private MessageService messageService;

	@Autowired
	private VideoProcessor videoProcessor;

	@RequestMapping("/stat")
	@ResponseBody
	public void bedMatWarningData(HttpServletRequest request, HttpServletResponse response) {
		// 数据处理
		String result = "";
		logger.debug("-----------------------------start test stat-------------------------------------");
		// sService.statInTryBackQuery();
		// sService.statConsultQuery();
		// sService.statOldManQuery();
		// s2Service.getTimeServiceItem(79);
		// dService.getDeviceFromAll("101", (short)1, "deviceType3",
		// "huamishouhuan");
		// cService.getCustomerLocationData(Long.parseLong("1014"),
		// Long.parseLong("1"));
		// dService.updateDeviceStatus();
		// Customer customer=new Customer();
		// customer.setId(280L);;
		// customer=cService.getCustomer(customer);
		// cService.operateCustomerBack(null, customer);
		// lService.addDeviceInfo("");
		// wService.sign("http://web.tnb99.cn");
		// cService.getCustomerByEID(12L);
		// nService.getNursingServiceByCustomer(null,20l,20l,24l,"postType5");

		// nService.getDrugProjectByCustomer(129L);
		// dService.getCustomerWithDeviceNo("11", "12");
		// sService.copyCusomerPlanDetail();
		// sService.createCustomerDayBill();
		// sService.createCustomerMonthBill();
		// wService.getCodeUrl("http://web.tnb99.cn/index.html?type=consumer");
		// dService.getCustomerWithDeviceNo("17c7f722","000017c7");
		// Date date1=new Date(2017-1900, 05, 05);
		// int interval = (int) ((System.currentTimeMillis() - date1.getTime())
		// / (1000*3600*24));
		// testService.deleteStatData();
		// Calendar cal = Calendar.getInstance();
		// cal.set(Calendar.YEAR, 2017);
		// cal.set(Calendar.MONTH, 05);
		// cal.set(Calendar.DAY_OF_MONTH, 5);
		// for(int i=0;i<interval-1;i++){
		// cal.add(Calendar.DATE, 1);
		// Date date = cal.getTime();
		// SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// String dateStr = sim.format(date);
		// System.out.println(dateStr);
		// testService.statInTryBackQuery(dateStr);
		// testService.statConsultQuery(dateStr);
		// testService.statOldManQuery(dateStr);
		// }
		// nursingService.getEmployeeByCID(129L);
		// employeeService.findByWorkTimeSetting(1002l,1498638371L) ;
		// sService.createCustomerDayBill();
		// nursingService.getCustomerByUID(19l);
		// nursingService.getProjectItemFromPlanDetail(129l, 1499307204);
		// CustomerServerChange change=new CustomerServerChange();
		// Customer customer=new Customer();
		// customer.setId(242l);
		// change.setId(199l);
		// change.setCustomer(customer);
		// cService.operateCustomerServerChange(change);
		// sService.createCustomerDayBill();
		// logger.debug("start test personlocation");
		// sService.sysPersonLocationReport();
		// sService.sysNightPersonLocationReport();
		// logger.debug("end test personlocation");
		// lService.addDeviceInfo("111");
		// sService.statStaffAttendance();
		// sService.statStaffWorkTime();
		// testService.attendance();
		// nursingService.getServicesExe(1504800000,1505367251,124l);
		// nursingService.getNursingServiceByCustomer(188l,null,0l,24l,null,null,"suishi");
		// aLiService.forbidLiveStream("live1.tnb99.net", "live1", "huibati");
		// aLiService.resumeLiveStream("live1.tnb99.net", "live1", "huibati");
		// statService.statServiceQueryForDay("(26,25)", 1509897600,
		// 1509984000);
		// statService.statServiceQueryForMonth("(26,25)", 1490976000,
		// 1493568000);
		// statService.statServiceQueryForQuarter("(26,25)", 1483200000,
		// 1490976000);
		// statService.statServiceQueryForYear("(26,25)", 1483200000,
		// 1514736000);
		// statService.statOntime("queryCustomer", 0, 0);
		// sService.statConsultQuery();
//		tenantService.addAllModeSourceData();
		
		testService.fabuTenant();
		
		// tenantService.addAllModeSourceData();
		ActionContextHolder.getLocalServerFlag().put("flag1", CommonUtil.getCurrTimes());
		BufferedOutputStream out;
		try {
			out = new BufferedOutputStream(response.getOutputStream());
			out.write("test stat end".getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.debug(" test stat error " + e);
		}
	}

	@RequestMapping("/back")
	@ResponseBody
	public void testCustomerBack(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("-----------------------------start test back-------------------------------------");
		testService.testCustomerBack();
		// List<CustomerBusinessFlow> flowYList = this.em
		// .createQuery(
		// "select a from CustomerBusinessFlow a where a.id = ?1 ")
		// .setParameter(1,291L)
		// .getResultList();
		// cService.operateCustomerBack(flowYList.get(0),flowYList.get(0).getCustomer(),0,new
		// HashMap<>());
		// testService.testTanPing();
		BufferedOutputStream out;
		try {
			out = new BufferedOutputStream(response.getOutputStream());
			out.write("test stat end".getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.debug(" test stat error " + e);
		}
	}

	@RequestMapping("/yesback")
	@ResponseBody
	public void testYesCustomerBack(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("-----------------------------start yes test back-------------------------------------");
		testService.testYesCustomerBack();
		BufferedOutputStream out;
		try {
			out = new BufferedOutputStream(response.getOutputStream());
			out.write("test yes stat end".getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.debug(" test stat error " + e);
		}
	}

	// 测试演示
	@RequestMapping("/startShow")
	@ResponseBody
	public void startShow(HttpServletRequest request, HttpServletResponse response) {
		// 数据处理
		logger.debug("-----------------------------show   start-------------------------------------");
		String param = request.getParameter("flag");
		Long tenantId = (long) -1;
		if (param != null && !"".equals(param) && param.matches("\\d+")) {
			tenantId = Long.parseLong(param);// 获取所传tenantid
		}
		testService.startShowDeviceData(tenantId);
		BufferedOutputStream out;
		try {
			out = new BufferedOutputStream(response.getOutputStream());
			out.write("show end".getBytes());
			out.flush();
			out.close();
		} catch (IOException e) {
			logger.debug("show  error:" + e);
		}
		logger.debug("-----------------------------show   end-------------------------------------");
	}

	// 测试演示
	@RequestMapping("/endShow")
	@ResponseBody
	public void endShow(HttpServletRequest request, HttpServletResponse response) {
		// 数据处理
		logger.debug("-----------------------------show   end-------------------------------------");
		testService.endShowDeviceData();
		BufferedOutputStream out;
		try {
			out = new BufferedOutputStream(response.getOutputStream());
			out.write("show end".getBytes());
			out.flush();
			out.close();
		} catch (IOException e) {
			logger.debug("show  error:" + e);
		}
		logger.debug("-----------------------------show   end-------------------------------------");
	}

	@RequestMapping("/removeFlag")
	@ResponseBody
	public void removeFlag(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("-----------------------------start test back-------------------------------------");
		String param = request.getParameter("flag");
		if (param != null && !"".equals(param) && param.matches("\\d+")) {
			ActionContextHolder.getPlanModelList().remove(param);
		} else {
			ActionContextHolder.getPlanModelList().clear();
		}
		BufferedOutputStream out;
		try {
			out = new BufferedOutputStream(response.getOutputStream());
			out.write("removeFlag".getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.debug(" test stat error " + e);
		}
	}

	// 收取本地服务推送的设备信息
	@RequestMapping("/call")
	@ResponseBody
	public void receiveDeviceData(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("---------------start receive hbeacon data-------------------------------------");
		BufferedReader in = null;
		String result = "";
		try {
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(request.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			result = "{\"callingData\":[{\"callingTime\":1491960821,\"deviceId\":\"cc1be0e8106b\"}],\"dataSource\":\"guihua\"}";// 呼叫
			// result="{\"deviceData\":[{\"deviceId\":\"fx000000000\",\"dataTime\":666666},{\"deviceId\":\"fx000000001\",\"dataTime\":666666}]}";//设备数据
			// result="{\"locationData\":[{\"dataTime\":1501635355,\"scanner\":\"feffaaf074fe\",\"deviceId\":\"d8b61a48a513\"}]}";//位置数据
			logger.debug("receive data " + result);
			if (result != null && !"".equals(result)) {
				// JSONObject data = JSONObject.fromObject(result);
				if (result.contains("callingData")) {// 按键呼叫信息
					testService.buildHbeaconCallingMessage(result);// 添加socket提醒信息
				}
				// if (result.contains("deviceData")) {// 设备以及信息
				// deviceService.updateDeviceStatusDate(result);// 更新设备状态时间
				// }
				// if (result.contains("locationData")) {// 位置信息
				// deviceService.updateDeviceLocationData(result);// 更新位置信息
				// }
				// if (result.contains("scannerStatus")) {// 扫描器状态信息
				// deviceService.updateScannerStatusData(result);// 更新扫描器状态信息
				// }
			}
			logger.debug("receiveDeviceData: " + result);
			BufferedOutputStream out;
			out = new BufferedOutputStream(response.getOutputStream());
			out.write("http ok".getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.debug("receiveDeviceData Exception: " + e.toString());
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				logger.debug("receiveDeviceData error " + ex);
			}
		}
		logger.debug("---------------end receive hbeacon data-------------------------------------");// 数据处理
	}

	// 收取本地服务推送的设备信息
	@RequestMapping("/backchange")
	@ResponseBody
	public void backChange(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("---------------start receive hbeacon data-------------------------------------");
		BufferedReader in = null;
		String result = "";
		try {
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(request.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			testService.operateBackAndServerChange();
			BufferedOutputStream out;
			out = new BufferedOutputStream(response.getOutputStream());
			out.write("http ok".getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.debug("receiveDeviceData Exception: " + e.toString());
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				logger.debug("receiveDeviceData error " + ex);
			}

		}
		logger.debug("---------------end receive hbeacon data-------------------------------------");// 数据处理
	}

	/*
	 * 测试视频直播
	 */
	@RequestMapping("/checkLive")
	@ResponseBody
	public void checkLive(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("-----------------------------startLive-------------------------------------");
		String code = request.getParameter("code");
		BufferedOutputStream out;
		try {
			String url = "rtmp://47.104.2.109:1935/hls/test";
			new LiveStreamListener().isStreamInLive(url);
			out = new BufferedOutputStream(response.getOutputStream());
			out.write("checkLive end".getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.error(" tenantCode error ", e);
		}
	}

	/*
	 * 测试视频直播
	 */
	@RequestMapping("/stopLive")
	@ResponseBody
	public void stopLive(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("-----------------------------stopLive-------------------------------------");
		String code = request.getParameter("code");
		BufferedOutputStream out;
		try {
			videoProcessor.stopRemoteLive("111",code);
			out = new BufferedOutputStream(response.getOutputStream());
			out.write("stopLive end".getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.error(" tenantCode error ", e);
		}
	}

	@RequestMapping("/tanping")
	@ResponseBody
	public void testTanPing(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("-----------------------------start test back-------------------------------------");
		testService.testTanPing();
		BufferedOutputStream out;
		try {
			out = new BufferedOutputStream(response.getOutputStream());
			out.write("test stat end".getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.debug(" test stat error " + e);
		}
	}

	@RequestMapping("/socketList")
	@ResponseBody
	public void testSocketList(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("-----------------------------start test back-------------------------------------");
		String res = "";
		for (String uid : ActionContextHolder.getUidSocketSessionHolder().keySet()) {
			res += " " + uid + ":";
			for (WebSocketSession session : ActionContextHolder.getUidSocketSessionHolder().get(uid)) {
				res += session.toString() + " ";
			}
			res += ";";
		}
		BufferedOutputStream out;
		try {
			out = new BufferedOutputStream(response.getOutputStream());
			out.write(res.getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.debug(" test stat error " + e);
		}
	}

	/*
	 * 测试视频直播
	 */
	@RequestMapping("/startLive")
	@ResponseBody
	public void startLive(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("-----------------------------startLive-------------------------------------");
		String code = request.getParameter("code");
		BufferedOutputStream out;
		try {
			LsMessage message = new LsMessage();
			message.setCode("2001");
			message.setDeviceCode(code);
			message.setPushType(1);
			messageService.sendMessageTols("ganen", message);
			out = new BufferedOutputStream(response.getOutputStream());
			out.write("startLive end".getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.error(" tenantCode error ", e);
		}
	}
}
